// ActionScript file
	import com.cliver.encryption.*;
	import com.nhn.maps.interfaces.IPoint;
	
	import mx.collections.XMLListCollection;
	import mx.rpc.events.ResultEvent;
	
	private var bType:String;
	private var tType:String;
	
	[Bindable] private var encodeQoute:String;
	[Bindable] private var encodePic:String;
	[Bindable] private var mainReportNum:String;
	[Bindable] private var getReportMode:String; // general or interlocked
	[Bindable] private var modifyingCommentStr:String;
	
	[Bindable] private var postingUid:String;
	[Bindable] private var postingApiKey:String;
	
	private var selectedReport:XMLListCollection;
	private var selectedReportBtype:String;
	private var selectedReportTtype:String;
	private var selectedReportCtStr:String;
	private var selectedReportDeReportComment:String;
	
	[Bindable] private var akey:String = "73ae3e1eadc42708952ff4f88c1acc96";
	[Bindable] private var auth_key:String;
	[Bindable] private var userId:String;
	[Bindable] private var postBody:Object;
	
	public function get_m2profile():void{
		if (ExternalInterface.available)
		{
			sid = ExternalInterface.call("send_sidToAS");
			displayName = ExternalInterface.call("send_dispNameToAS");
			myThumbPicUrl = ExternalInterface.call("send_thumbPicToAS");
		}
		
		if(Boolean(sid)==false){sid="TesterSID"; displayName="테스터팀아이디"; myThumbPicUrl = 'img/testerThumbnail.png';}
		containerKeyInit();
	}
	
	public function viewProfile():void{
		interpretMainReport();
		
		lab_dispName.text = displayName;
		img_proPic.source = myThumbPicUrl;
		cbx_mySex.data = (Boolean(mySex)) ? mySex : "";
		txt_myAge.text = myAge.toString();
		
		lab_bType.text = (bType.length > 1) ? bType : "main Report를 지정하세요";
		lab_tType.text = (tType.length > 1) ? tType : "main Report를 지정하세요";
		
		area_myQoute.text = myQoute;
		
		viewLatLng();
		txt_notiSaveProfile.text = "변경된 내용을 반영하려면 Save 버튼을 눌러주세요";
		if(Boolean(mySex)==false && Boolean(myAge)==false){
			txt_notiSaveProfile.text="프로필을 저장하지 않으셨습니다.";
		}
	}
	
	private function getDBProfile(event:ResultEvent):void{
		dataset_profile = new XMLListCollection(new XMLList(event.result));
		if(dataset_profile.child("sex").text().toString()=="Man"){	mySex = "Man";	}else if(dataset_profile.child("sex").text().toString()=="Woman"){	mySex = "Woman";	}
		myAge = int(dataset_profile.child("age"));
		lat = Number(dataset_profile.child("lat").text());
		lng = Number(dataset_profile.child("lng").text());
		mainReportNum = dataset_profile.child("mainReport").text().toString();
		reqGetMainReport.send(); // -> getMainReport()
		viewLatLng();
	}
	
	private function getQoute(event:ResultEvent):void{
		encodeQoute = event.result.toString();
		myQoute = unescape(encodeQoute);
		area_myQoute.text = myQoute;
	}
	
	private function saveProfile():void{
		encodeDName = escape(displayName);
		mySex = cbx_mySex.selectedLabel;
		myAge = int(txt_myAge.text);
		myQoute = area_myQoute.text;
		encodeQoute = escape(myQoute);
		encodePic = escape(myThumbPicUrl);
		reqSetProfile.send();
		reqSetQoute.send();
		txt_notiSaveProfile.text = "바뀐 프로필이 저장되었습니다."
	}
	
	private function deleteSelectedReport():void{
		if(dgrid_report.selectedItem != null){
			// delete Report in Database.
			reqDeleteSelectedReport.send();
			reqGetReport.send();
		}
	}
	
	private function getReport(event:ResultEvent):void{
		dataset_report.removeAll();
		dataset_report = new XMLListCollection(new XMLList(event.result.report));
		
		lab_lastReport.text = "마지막 검사 : "+calculateLastReport(dataset_report);
	}
	
	private function calculateLastReport(reports:XMLListCollection):String{
		var reportCount:int = (Boolean(reports)) ? reports.length : 0 ;
		var nowDate:Date = new Date();
		var lastDate:Date = new Date(2010,0,1);
		var diffDate:int = getDaysDiff(nowDate, lastDate);
		var returnDate:String = "없음";
		
		for(var i:int=0; i<reportCount; i++){
			var scD:String = reports[i].child("testNum").substr(-14,14); // slicedDate
			var reportDate:Date = new Date(Number(scD.substr(0,4)), Number(scD.substr(4,2))-1, Number(scD.substr(6,2)));
			
			if(lastDate < reportDate){
				lastDate = reportDate;
				diffDate = getDaysDiff(nowDate, lastDate);
			}
		}
		
		if(diffDate>28){	returnDate = "수 개월 전";	}
		else if(diffDate>21){	returnDate = "3 주 전";	}
		else if(diffDate>14){	returnDate = "2 주 전";	}
		else if(diffDate>7){	returnDate = "지난 주";	}
		else if(diffDate>=3){	returnDate = diffDate.toString()+"일 전";	}
		else if(diffDate==2){	returnDate = "그저께";	}
		else if(diffDate==1){	returnDate = "어제";		}
		else if(diffDate==0){	returnDate = "오늘";		}
		else{			returnDate = "알 수 없음";		}
		
		return returnDate;
	}
	
	private function reviewReport():void{
		var selectedReport:XMLListCollection = new XMLListCollection(new XMLList(dgrid_report.selectedItem.valueOf()));
		reportNum = selectedReport.child("testNum").text().toString();
		
		var sidCharLength:int = reportNum.length - 16;
		
		var reportVal:String = selectedReport.child("combinedPoint").text().toString();
		var reportDay:String = (reportNum.substr(sidCharLength+2,4)+"."+reportNum.substr(sidCharLength+6,2)+"."+reportNum.substr(sidCharLength+8,2)+" "+reportNum.substr(sidCharLength+10,2)+":"+reportNum.substr(sidCharLength+12,2)+":"+reportNum.substring(sidCharLength+14));
		var deReportComment:String = unescape(selectedReport.child("comment").text().toString());
		
		var selectedTestType:String = reportNum.substr(sidCharLength+1,1);
		var eS:int=int(reportVal.substr(0,2));	var eN:int=int(reportVal.substr(2,2));
		var eT:int=int(reportVal.substr(4,2));	var eF:int=int(reportVal.substr(6,2));
		var iS:int=int(reportVal.substr(8,2));	var iN:int=int(reportVal.substr(10,2));
		var iT:int=int(reportVal.substr(12,2));	var iF:int=int(reportVal.substr(14,2));

		var bType:String = analizeBasicType(eS,eN,eT,eF,iS,iN,iT,iF);
		var tType:String = analizeTendenciatedType(eS,eN,eT,eF,iS,iN,iT,iF);
		var reliability:String = analizeReliability(eS,eN,eT,eF,iS,iN,iT,iF);
		var maxPoint:int;
		var report:String="";
		
		if(selectedTestType == "B"){
			maxPoint = 40;
		}else if(selectedTestType == "S"){
			maxPoint = 120;
		}
		
		if(selectedTestType == "B"){report += "검사종류 : 기본검사\r";	}else if(selectedTestType == "S"){report += "검사종류 : 단순문항검사\r";}
		
		var eC:int = 0; var iC:int = 0; var CtStr:String = "";
		CtStr = analizeFocusTendenciation(eS+eN+eT+eF, iS+iN+iT+iF);
		
		report += "검사일자 : "+reportDay+"\r";
		report += "기본유형 : "+bType+"\r";
		report += "경향화유형 : "+tType+"\r";
		report += "경향화방향 : "+CtStr+"\r";
		report += "검사정확도 : "+reliability+"%"+" (정확도가 높을 수록, 검사결과로 나온 기본유형이 당신의 선천적인 유형이라고 믿어도 좋습니다.)\r";
		report += "유형편향도 : "+((eS+eN+eT+eF+iS+iN+iT+iF)/maxPoint*100).toString().substr(0,5)+"%"+" (편향도가 높을 수록, 현재 당신의 경향화 상태가 강하다는 뜻입니다.)\r";
		report += "지표별 점수 : "+"eS:"+eS+", "+"eN:"+eN+", "+"eT:"+eT+", "+"eF:"+eF+", "+"iS:"+iS+", "+"iN:"+iN+", "+"iT:"+iT+", "+"iF:"+iF+"\r\r";
		report += "남긴 코멘트 : "+deReportComment+"\r";
		
		area_reviewReport.text = report;
	}
	
	private function viewDetailReportInfo():void{
		selectedReport = new XMLListCollection(new XMLList(dgrid_report.selectedItem.valueOf()));
		reportNum = selectedReport.child("testNum").text().toString();
		
		var sidCharLength:int = reportNum.length - 16;
		
		var reportVal:String = selectedReport.child("combinedPoint").text().toString();
		var reportDay:String = (reportNum.substr(sidCharLength+2,4)+"."+reportNum.substr(sidCharLength+6,2)+"."+reportNum.substr(sidCharLength+8,2)+" "+reportNum.substr(sidCharLength+10,2)+":"+reportNum.substr(sidCharLength+12,2)+":"+reportNum.substring(sidCharLength+14));
		var deReportComment:String = unescape(selectedReport.child("comment").text().toString());
		
		var selectedTestType:String = reportNum.substr(sidCharLength+1,1);
		var eS:int=int(reportVal.substr(0,2));	var eN:int=int(reportVal.substr(2,2));
		var eT:int=int(reportVal.substr(4,2));	var eF:int=int(reportVal.substr(6,2));
		var iS:int=int(reportVal.substr(8,2));	var iN:int=int(reportVal.substr(10,2));
		var iT:int=int(reportVal.substr(12,2));	var iF:int=int(reportVal.substr(14,2));

		var bType:String = analizeBasicType(eS,eN,eT,eF,iS,iN,iT,iF);
		var tType:String = analizeTendenciatedType(eS,eN,eT,eF,iS,iN,iT,iF);
		var G1:int = eS+eT+iN+iF;		var G2:int = eS+eF+iN+iT;
		var G3:int = eN+eT+iS+iF;		var G4:int = eN+eF+iS+iT;
		var totalPoint:int = eS+eN+eT+eF+iS+iN+iT+iF;
		var reliability:String = analizeReliability(eS,eN,eT,eF,iS,iN,iT,iF);
		var maxPoint:int;
		var reportType:String="";
		var reportCommon:String="";
		
		if(selectedTestType == "B"){
			maxPoint = 40;
		}else if(selectedTestType == "S"){
			maxPoint = 120;
		}
		
		if(selectedTestType == "B"){reportCommon += "검사종류 : 기본검사\r";	}else if(selectedTestType == "S"){reportCommon += "검사종류 : 단순문항검사\r";}
		reportCommon += "검사일자 : "+reportDay+"\r";
		
		var eC:int = 0; var iC:int = 0; var CtStr:String = "";
		CtStr = analizeFocusTendenciation(eS+eN+eT+eF, iS+iN+iT+iF);
		
		reportType += "지표별 점수 : "+"eS:"+eS+", "+"eN:"+eN+", "+"eT:"+eT+", "+"eF:"+eF+", "+"iS:"+iS+", "+"iN:"+iN+", "+"iT:"+iT+", "+"iF:"+iF+"\r\r";
		reportType += "기본유형 : "+bType+"\r";
		reportType += "경향화유형 : "+tType+"\r";
		reportType += "경향화방향 : "+CtStr+"\r";
		reportType += "검사정확도 : "+reliability+"% \r";
		reportType += "유형편향도 : "+((eS+eN+eT+eF+iS+iN+iT+iF)/maxPoint*100).toString().substr(0,5)+"% \r";
		reportType += "각 군별 일치율 : \r"+"G1 : "+(100*G1/totalPoint).toString().substr(0,5)+"% \rG2 : "+(100*G2/totalPoint).toString().substr(0,5)+"% \rG3 : "+(100*G3/totalPoint).toString().substr(0,5)+"% \rG4 : "+(100*G4/totalPoint).toString().substr(0,5)+"% \r";
		if(Boolean(dgrid_report.selectedItem)){
			tnav_profile.selectedChild = can_detailReportInfo;
		}
		
		area_detailReportInfoType.text = reportType;
		area_detailReportInfoDay.text = reportCommon;
		area_detailReportInfoComment.text = deReportComment;
		
		selectedReportBtype = bType
		selectedReportTtype = tType;
		selectedReportCtStr = CtStr;
		selectedReportDeReportComment = deReportComment;
	}
	
	private function requestSaveMainReport():void{
		var selectedReport:XMLListCollection = new XMLListCollection(new XMLList(dgrid_report.selectedItem.valueOf()));
		reportNum = selectedReport.child("testNum").text().toString();
		
		if(reportNum.length >= 1){
			mainReportNum = reportNum;
			reqSetMainReport.send();

		}else{
			lab_mainReportNotification.text = "메인리포트로 지정할 검사항목을 선택해주세요.";
		}
	}
	
	private function savedMainReport():void{
		reqGetMainReport.send();
		interpretMainReport();
		lab_mainReportNotification.text = mainReportNum+"번 검사가 main Report로 지정되었습니다.";
		lab_bType.text = bType;
		lab_tType.text = tType;
	}
	
	
	private function interpretMainReport():void{
		var reportVal:String = dataset_mainReport.child("combinedPoint").text().toString();
		
		if(int(reportVal) == 0){
			bType="";	tType="";
		}else{
			var eS:int=int(reportVal.substr(0,2));	var eN:int=int(reportVal.substr(2,2));
			var eT:int=int(reportVal.substr(4,2));	var eF:int=int(reportVal.substr(6,2));
			var iS:int=int(reportVal.substr(8,2));	var iN:int=int(reportVal.substr(10,2));
			var iT:int=int(reportVal.substr(12,2));	var iF:int=int(reportVal.substr(14,2));
			bType = analizeBasicType(eS,eN,eT,eF,iS,iN,iT,iF);
			tType = analizeTendenciatedType(eS,eN,eT,eF,iS,iN,iT,iF);
		}
			
	}
		
	private function getMainReport(event:ResultEvent):void{
		dataset_mainReport.removeAll();
		dataset_mainReport = new XMLListCollection(new XMLList(event.result));
	}
	
	private function requestViewMainReport():void{
		reqGetMainReport.send();
		reportNum = dataset_mainReport.child("testNum").text().toString();
		var sidCharLength:int = reportNum.length - 16;
		
		if(Boolean(reportNum) == true){
			var reportVal:String = dataset_mainReport.child("combinedPoint").text().toString();
			var reportDay:String = (reportNum.substr(sidCharLength+2,4)+"."+reportNum.substr(sidCharLength+6,2)+"."+reportNum.substr(sidCharLength+8,2)+" "+reportNum.substr(sidCharLength+10,2)+":"+reportNum.substr(sidCharLength+12,2)+":"+reportNum.substring(sidCharLength+14));
			var deReportComment:String = unescape(dataset_mainReport.child("comment").text().toString());
			
			var selectedTestType:String = reportNum.substr(sidCharLength+1,1);
			var eS:int=int(reportVal.substr(0,2));	var eN:int=int(reportVal.substr(2,2));
			var eT:int=int(reportVal.substr(4,2));	var eF:int=int(reportVal.substr(6,2));
			var iS:int=int(reportVal.substr(8,2));	var iN:int=int(reportVal.substr(10,2));
			var iT:int=int(reportVal.substr(12,2));	var iF:int=int(reportVal.substr(14,2));
			
			var bType:String = analizeBasicType(eS,eN,eT,eF,iS,iN,iT,iF);
			var tType:String = analizeTendenciatedType(eS,eN,eT,eF,iS,iN,iT,iF);
			var reliability:String = analizeReliability(eS,eN,eT,eF,iS,iN,iT,iF);
			var maxPoint:int;
			
			var eC:int = 0; var iC:int = 0; var CtStr:String = "";
			CtStr = analizeFocusTendenciation(eS+eN+eT+eF, iS+iN+iT+iF);

			if(selectedTestType == "B"){
				maxPoint = 40;
			}else if(selectedTestType == "S"){
				maxPoint = 120;
			}

			
			var report:String="";
			if(selectedTestType == "B"){report += "검사종류 : 기본검사\r";	}else if(selectedTestType == "S"){report += "검사종류 : 단순문항검사\r";}
			report += "검사일자 : "+reportDay+"\r";
			report += "기본유형 : "+bType+"\r";
			report += "경향화유형 : "+tType+"\r";
			report += "경향화방향 : "+CtStr+"\r";
			report += "검사정확도 : "+reliability+"%"+" (정확도가 높을 수록, 검사결과로 나온 기본유형이 당신의 선천적인 유형이라고 믿어도 좋습니다.)\r";
			report += "유형편향도 : "+((eS+eN+eT+eF+iS+iN+iT+iF)/maxPoint*100).toString().substr(0,5)+"% (편향도가 높을 수록, 현재 당신의 경향화 상태가 강하다는 뜻입니다.)\r";			
			report += "지표별 점수 : "+"eS:"+eS+", "+"eN:"+eN+", "+"eT:"+eT+", "+"eF:"+eF+", "+"iS:"+iS+", "+"iN:"+iN+", "+"iT:"+iT+", "+"iF:"+iF+"\r\r";
			report += "남긴 코멘트 : "+deReportComment+"\r";
			
			area_reviewReport.text = report;
			lab_mainReportNotification.text = "main Report : "+mainReportNum+" 를 불러왔습니다.";
		}else{
			area_reviewReport.text = "";
			lab_mainReportNotification.text = "main Report : 저장된 메인리포트가 없습니다.";
		}
	}
	
	[Bindable] private var mChartBtypes:ArrayCollection;
	[Bindable] private var mChartTtypes:ArrayCollection;
	private var pSFM:int, pNTV:int, pSTM:int, pNFV:int, pNFM:int, pSTV:int, pNTM:int, pSFV:int;
	private var pSTJ:int, pNTJ:int, pSFJ:int, pNFJ:int, pSTP:int, pSFP:int, pNTP:int, pNFP:int;
	
	
	
	private function mChartByBtype():void{
		if(dataset_report.length >= 2){
			calculateBtypesInMChart();
			pct_mChart.dataProvider = mChartBtypes;
			lab_mChartNotibar.text = "기본유형 빈도별 차트 조회완료.";
		}else if(dataset_report.length == 1){
			lab_mChartNotibar.text = "차트는 2건 이상의 결과에 대해서만 지원됩니다."
		}else{
			lab_mChartNotibar.text = "테스트를 먼저 진행하세요.";
		}
	}
	
	private function mChartByTtype():void{
		if(dataset_report.length >= 2){
			calculateTtypesInMChart();
			pct_mChart.dataProvider = mChartTtypes;
			lab_mChartNotibar.text = "경향화유형 빈도별 차트 조회완료.";
		}else if(dataset_report.length == 1){
			lab_mChartNotibar.text = "차트는 2건 이상의 결과에 대해서만 지원됩니다."
		}else{
			lab_mChartNotibar.text = "테스트를 먼저 진행하세요.";
		}
	}
	
	private function calculateBtypesInMChart():void{
		pSFM = pNTV = pSTM = pNFV = pNFM = pSTV = pNTM = pSFV = 0;
		var collectReport:ArrayCollection = new ArrayCollection;
		
		try{
		for (var i:int=0; dataset_report.length-1; i++){
			var combinedPoint:String = dataset_report[i].child("combinedPoint");
			var Btype:String = cpToType(combinedPoint, "B");
			pSFM += (Btype == "SFM")?1:0;	pNTV += (Btype == "NTV")?1:0;	pSTM += (Btype == "STM")?1:0;	pNFV += (Btype == "NFV")?1:0;
			pNFM += (Btype == "NFM")?1:0;	pSTV += (Btype == "STV")?1:0;	pNTM += (Btype == "NTM")?1:0;	pSFV += (Btype == "SFV")?1:0;
		}}catch(e:Error){}

		mChartBtypes = new ArrayCollection([
		{type:"SFM", freq:pSFM},{type:"NTV", freq:pNTV},{type:"STM", freq:pSTM},{type:"NFV", freq:pNFV},
		{type:"NFM", freq:pNFM},{type:"STV", freq:pSTV},{type:"NTM", freq:pNTM},{type:"SFV", freq:pSFV}]);
	}
	
	private function calculateTtypesInMChart():void{
		pSTJ = pNTJ = pSFJ = pNFJ = pSTP = pSFP = pNTP = pNFP = 0;
		var collectReport:ArrayCollection = new ArrayCollection;
		
		try{
		for (var i:int=0; dataset_report.length-1; i++){
			var combinedPoint:String = dataset_report[i].child("combinedPoint");
			var Ttype:String = cpToType(combinedPoint, "T");
			pSTJ += (Ttype == "STJ")?1:0;	pNTJ += (Ttype == "NTJ")?1:0;	pSFJ += (Ttype == "SFJ")?1:0;	pNFJ += (Ttype == "NFJ")?1:0;
			pSTP += (Ttype == "STP")?1:0;	pSFP += (Ttype == "SFP")?1:0;	pNTP += (Ttype == "NTP")?1:0;	pNFP += (Ttype == "NFP")?1:0;
		}}catch(e:Error){}

		mChartTtypes = new ArrayCollection([
		{type:"STJ", freq:pSTJ},{type:"NTJ", freq:pNTJ},{type:"SFJ", freq:pSFJ},{type:"NFJ", freq:pNFJ},
		{type:"STP", freq:pSTP},{type:"SFP", freq:pSFP},{type:"NTP", freq:pNTP},{type:"NFP", freq:pNFP}]);
	}
	
	private function cpToType(combinedPoint:String, mode:String):String{

		var eS:int=int(combinedPoint.substr(0,2));	var eN:int=int(combinedPoint.substr(2,2));
		var eT:int=int(combinedPoint.substr(4,2));	var eF:int=int(combinedPoint.substr(6,2));
		var iS:int=int(combinedPoint.substr(8,2));	var iN:int=int(combinedPoint.substr(10,2));
		var iT:int=int(combinedPoint.substr(12,2));	var iF:int=int(combinedPoint.substr(14,2));	
		var type:String;
		
		switch(mode){
			case "B" : 	type = analizeBasicType(eS,eN,eT,eF,iS,iN,iT,iF); 			break;
			case "T" :	type = analizeTendenciatedType(eS,eN,eT,eF,iS,iN,iT,iF);	break;
		}
		
		return type;
	}
	
	private function viewMChartLabel(data:Object, field:String, index:Number, percentValue:Number):String{
		return data.type;
	}
	
	private function goAgreeInfomationProviding():void{
		tnav_main.selectedChild = can_guide;
		cbx_SubGuide.dataProvider = HelpGuideArr;
		reqGetGuideText.url = "text/AgreeInfomationProviding.txt";
		reqGetGuideText.send();
		
		cbx_MainGuide.selectedItem = "앱 도움말"
		cbx_SubGuide.dataProvider = HelpGuideArr;
		cbx_SubGuide.selectedItem = "개인정보제공 동의 및 한계"
	}
	
	private function deleteAllPersonalData():void{
		reqDeleteAllMsg.send();
		reqDeleteAllPersonalData.send();
	}
	
	private function deletedAllPersonalData():void{
		init();
		map.destroy();
		dataset_message.removeAll();
		mySex = "";
		cbx_mySex.data = "";
		txt_myAge.text = "";
		lab_bType.text = "";
		lab_tType.text = "";
		
		
		lab_locationNotification.text = "위치정보가 삭제되었습니다.";
		lab_notiLocationSave.text = "지역정보는 이용자정보가 저장되어 있어야, 저장가능합니다.";
		Alert.show("나이와 성별,지역정보 등의 프로필 정보와 시행한 검사결과, 쪽지함의 데이터가 모두 삭제되었습니다.\r\r그동안 이용해주셔서 감사합니다.\r이제 안전하게 앱을 삭제하셔도 됩니다.");
	}
	
	private function modifyComment():void{
		modifyingCommentStr = escape(area_detailReportInfoComment.text);
		reqModifyComment.send();
	}
	
/** 네이버 지도 */
	private var map:NMap;
	private var indexMap:NIndexMap;
	private var zoomControl:NZoomControl;
	private var placeMark:NPlaceMark;
	
	private function startMap(event:Event):void{
		map = new NMap(map_me, "a079f51c014345ba47308581584ec380", map_me.width, map_me.height);
		map.addEventListener(NMapEvent.INIT, onMapInitHandler);
		map.addEventListener(NMapEvent.DRAG, onMapMoveHandler);
	    map.coordType = NCoordType.WGS84;
	}
	
	private function viewLatLng():void{
		if(lat.toString().length >=2 && lng.toString().length >=2){
			var point:IPoint = new NLatLng(lat, lng);
			map.setCenter(point);
			placeMark.setPoint(map.getCenter());
			
			lat = (Boolean(lat))?lat:0;	lng = (Boolean(lng))?lng:0;
			tput_location.text = "위도 : "+lat+", 경도 : "+lng;
		}
	}
	
	private function createMarker():void{
		var markParams:NMarkParams = new NMarkParams();
		markParams.label = "내 위치";
		markParams.labelTextFormat = new TextFormat("Dotum", 12, 0x000000, true);
		markParams.dragEnabled = false;
            
		/**  위치마크 객체를 생성한다. 지도의 중심 좌표와 마커 속성을 인자값으로 설정한다. */
		placeMark = new NPlaceMark(map.getCenter(), markParams);
		map.addOverlay(placeMark);
	}
            
	// 지도 객체가 초기화 되었을 때  처리 @param event mapInit 이벤트
	private function onMapInitHandler(event:NMapEvent):void{
		var initLat:Number;
		var initLng:Number;
		if(lat.toString().length>=2 && lng.toString().length>=2){
			initLat = lat;	initLng = lng;
		}else{
			initLat = 1.0000000;	initLng = 1.0000000;
			lab_locationNotification.text = "지역정보를 저장하지 않으셨습니다."
		}
		
		map.setCenterAndZoom(new NLatLng(initLat, initLng), 7);
                
		// 줌 컨트롤러 객체를 생성한다.
		zoomControl = new NZoomControl();
                
		// 지도내에서의 수평/수직 정렬을 설정한다.
		zoomControl.setAlign(HorizontalAlignment.RIGHT);
		zoomControl.setVAlign(VerticalAlignment.TOP);
                
		// 줌 컨트롤러를 지도에 추가한다.
		map.addControl(zoomControl);
                
		// 미니맵 객체를 생성한다. 설정방법은 줌 컴트롤러와 동일한다.
		indexMap = new NIndexMap();
		indexMap.setAlign(HorizontalAlignment.RIGHT);
		indexMap.setVAlign(VerticalAlignment.BOTTOM);
		map.addControl(indexMap);
		createMarker();
		refreshLatLng();
	}
	
	private function onMapMoveHandler(event:NMapEvent):void{
		placeMark.setPoint(map.getCenter());
		refreshLatLng();
	}
	
	private function refreshLatLng():void{
		tput_location.text = "위도 : "+map.getCenter().y+", 경도 : "+map.getCenter().x;
		lat = map.getCenter().y;	lng = map.getCenter().x;
		
	}
	
	private function saveLocation():void{
		lab_notiLocationSave.text = "";
		reqSetLocation.send();
	}
	
	private function savedLocation():void{
		lab_locationNotification.text = "지역정보가 갱신되었습니다.";
	}
	
	
	
/** 커넥트 */
	[Bindable] private var thisContainerName:String;
	[Bindable] private var naverBlogKey:String = "";
	[Bindable] private var naverCafeKey:String = "";
	[Bindable] private var naverMetooKey:String = "";
	[Bindable] private var cyworldKey:String = "";
	
	private function validateContainer():void{
		if(sid.length == 19){
			switch(sid.substr(0,2)){
				case "11":
					thisContainerName = "naverBlog";
					break;
				case "12":
					thisContainerName = "naverCafe";
					break;
				case "13":
					thisContainerName = "naverMetoo";
					break;
			}
		}else if(sid.length == 8){
			thisContainerName = "cyworld";
		}
	}
	
	private function containerKeyInit():void{
		if(sid.length == 19){
			switch(sid.substr(0,2)){
				case "11":
					thisContainerName = "naverBlog";
					tput_naverBlogKey.text = sid;
					break;
				case "12":
					thisContainerName = "naverCafe";
					tput_naverCafeKey.text = sid;
					break;
				case "13":
					thisContainerName = "naverMetoo";
					tput_naverMetooKey.text = sid;
					break;
			}
		}else if(sid.length == 8){
			thisContainerName = "cyworld";
			tput_cyworldKey.text = sid;
		}
		reqGetContainerKey.send();
	}
	
	private function loadedContainerKey(event:ResultEvent):void{
		dataset_containerKey.removeAll();
		dataset_containerKey = new XMLListCollection(new XMLList(event.result));
		try{
		tput_naverBlogKey.text = naverBlogKey = dataset_containerKey.child("naverBlog");
		tput_naverCafeKey.text = naverCafeKey = dataset_containerKey.child("naverCafe");
		tput_naverMetooKey.text = naverMetooKey = dataset_containerKey.child("naverMetoo");
		tput_cyworldKey.text = cyworldKey = dataset_containerKey.child("cyworld");
		}catch(e:Error){}
		
		getReportMode = (Boolean(naverBlogKey)==false && Boolean(naverCafeKey)==false && Boolean(naverMetooKey)==false) ? "general" : "interlocked";
	}
	
	private function issueContainerKey():void{
		if(sid.length == 19){
			switch(sid.substr(0,2)){
				case "11":
					lab_containerName.text = "컨테이너 : 네이버 블로그";
					tput_containerKey.text = sid;
					break;
				case "12":
					lab_containerName.text = "컨테이너 : 네이버 카페";
					tput_containerKey.text = sid;
					break;
				case "13":
					lab_containerName.text = "컨테이너 : 네이버 미투데이";
					tput_containerKey.text = sid;
					break;
			}
		}else if(sid.length == 8){
			lab_containerName.text = "컨테이너 : 싸이월드";
			tput_containerKey.text = sid;
		}
		/*
		else if(sid.length == "nate sid 자리 수 "){
			// nate 처리 code
		}
		else if(sid.length == "facebook 자리 수"){
			// facebook 처리 code
		}
		*/
	}
	
	private function activateInterlocking():void{
		naverBlogKey = tput_naverBlogKey.text;
		naverCafeKey = tput_naverCafeKey.text;
		naverMetooKey = tput_naverMetooKey.text;
		cyworldKey = tput_cyworldKey.text;
		getReportMode = (Boolean(naverBlogKey)==false && Boolean(naverCafeKey)==false && Boolean(naverMetooKey)==false && Boolean(cyworldKey)==false) ? "general" : "interlocked";
		
		reqSetContainerKey.send();
	}
	
	private function savedContainerKey():void{
		reqGetReport.send();
	}
	
	private function deleteInterlocking():void{
		reqDeleteInterlocking.send();
		tput_naverBlogKey.text = naverBlogKey = "";
		tput_naverCafeKey.text = naverCafeKey = "";
		tput_naverMetooKey.text = naverMetooKey = "";
		tput_cyworldKey.text = cyworldKey = "";
		
		getReportMode = "general";
	}
	
/** Metoo API 글쓰기*/
	
	private function checkApiKey():void{
		if(Boolean(tput_postUid.text)){
			link('http://me2day.net/'+tput_postUid.text+'/setting');
		}else{
			lab_postingNoti.text = "미투데이 아이디를 입력하시고 'API키 확인'을 누르세요."
		}
	}
	
	private function postPreview():void{
		var postPreviewText:String = '"끼리끼리":http://apps.naver.com/app/22954';
		if(chk_postType.selected){
			postPreviewText += " 기본:" + selectedReportBtype;
			postPreviewText += " 경향:" + selectedReportTtype;
		}
		if(chk_postPercentage.selected){
			postPreviewText += " " + selectedReportCtStr;
		}
		if(chk_postComment.selected){
			postPreviewText += " " + selectedReportDeReportComment;
		}
		
		area_postPreview.text = postPreviewText;
	}
	
	private function postReport():void{
		if(Boolean(area_postPreview.text) && Boolean(tput_postApiKey.text) && Boolean(tput_postUid.text)){
			var nonce:String = "00000000";
			var user_key:String = tput_postApiKey.text;
			auth_key = nonce + MD5.encrypt(nonce + user_key);
			userId = tput_postUid.text;
			postBody = area_postPreview.text;
			
			var params:Object = new Object();
			params["post[body]"] = postBody;
			params["uid"] = userId;
			params["akey"] = akey;
			params["ukey"] = auth_key;
			
			reqReportPosting.url = "http://www.me2day.net/api/create_post/"+userId+".xml";
			reqReportPosting.send(params);
			
			lab_postingNoti.text = "포스팅 실패, 아이디와 api키를 다시 확인해주세요.";
		}
		else if(Boolean(area_postPreview.text) == false){
			lab_postingNoti.text = "포스팅할 내용이 없습니다.";
		}else if(Boolean(tput_postApiKey.text) == false){
			lab_postingNoti.text = "Api 키를 입력해주세요.";
		}else if(Boolean(tput_postUid.text) == false){
			lab_postingNoti.text = "미투 아이디를 입력해주세요.";
		}
	}
	
	private function postedReport(event:ResultEvent):void{
		lab_postingNoti.text = "포스팅 완료";
		
		postingUid = tput_postUid.text;
		postingApiKey = tput_postApiKey.text;
		
		reqSavePostingCfg.send();
		
		chk_postType.selected = false;
		chk_postPercentage.selected = false;
		chk_postComment.selected = false;
		area_postPreview.text = "";
	}
	
	private function loadedPostingCfg(event:ResultEvent):void{
		var dataset_result:XMLListCollection = new XMLListCollection(new XMLList(event.result));
		tput_postUid.text = dataset_result.child("uid").text().toString();
		tput_postApiKey.text = dataset_result.child("naverMetoo").text().toString();
	}
	